<template>
    <div class="iaa-page">
        <span class="article-title">IAA配置管理</span>
        <div class="fliter">
            <span style="font-size: 14px;">应用名称：</span>
            <el-input v-model="applicationName" style="width: 250px;margin-right: 10px;" placeholder="请输入应用名称"
                clearable />
            <span style="font-size: 14px;">渠道分组：</span>
            <el-select v-model="groupId" placeholder="请选择渠道分组" style="width: 250px;margin-right: 10px;" clearable>
                <el-option v-for="item in groupOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>

            <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>

        </div>
        <div class="article-table">
            <el-button type="primary" @click="handleAddIaa()">+ 添加</el-button>
            <el-table ref="tableRef" :data="tableData" v-loading="loading" :row-key="'id'"
                :header-cell-style="{ background: '#fafafa', height: '56px', }"
                style="width: 100%;margin-top: 20px;margin-bottom: 20px; height: calc(100% - 70px);">
                <template v-for="(item, index) in tableHeader" :key="index">
                    <el-table-column :prop="item.prop" :label="item.label" :min-width="item.width" :fixed="index === 0"
                        :show-overflow-tooltip="item.prop === 'trackingLink' ? true : false">
                        <template #default="scope">
                            <div v-if="item.prop === 'icon' && scope.row[item.prop]" style="width: 45px; height:45px;">
                                <img style="width: 100%; height: 100%" :src="scope.row[item.prop]" />
                            </div>
                            <span v-else>{{ scope.row[item.prop] }}</span>
                        </template>
                    </el-table-column>
                </template>
                <el-table-column label="操作" width="190" fixed="right">
                    <template #default="scope">
                        <div style="display: flex;align-items: center;gap: 15px;flex-wrap: wrap;">
                            <span style="cursor: pointer;color: #1677ff;"
                                @click="handleEdit('edit', scope.row)">编辑</span>
                            <span style="cursor: pointer;color: red;" @click="handleDelete(scope.row.id)">删除</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <IaaAdd ref="iaaAdd" @getData="handleSearch" />
            <!-- <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize"
                style="display: flex;justify-content: end;" layout="total,prev, pager, next,sizes" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" /> -->
        </div>
    </div>
</template>

<script setup lang="ts">
import { defineComponent, onActivated, onMounted, ref } from 'vue';
import service from '../config';
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import IaaAdd from '../components/iaaAdd.vue'
import Sortable from 'sortablejs'
defineComponent({ name: 'IAA' })
const applicationName = ref('')
const tableData = ref([])
const groupId = ref(null)
const groupOptions = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref()
const loading = ref(false)
const iaaAdd = ref<{ openModal: (type?: string, id?: string) => void }>()
const tableHeader = ref([
    { label: 'ID', prop: 'id', width: 200 },
    { label: 'App图标', prop: 'icon', width: 200 },
    { label: '应用名称', prop: 'applicationName', width: 200 },
    { label: '简介', prop: 'intro', width: 200 },
    { label: '跟踪链接', prop: 'trackingLink', width: 200 },
])


const handleSearch = () => {
    loading.value = true
    service.post('/game/list', { applicationName: applicationName.value, groupId: groupId.value })
        .then(response => {
            loading.value = false
            tableData.value = response.data
            // total.value = response?.data?.total
            initRowDrag()
        })
        .catch(error => {
            loading.value = false
            console.error('Error fetching data:', error);
        });
}


const handleAddIaa = () => {
    iaaAdd.value?.openModal('add')
}

const handleEdit = (type, row) => {
    iaaAdd.value?.openModal(type, row)
}



const handleDelete = (id: string) => {
    service.get(`/game/delete`, { params: { id } })
        .then(response => {
            handleSearch()
            ElMessage.success('删除成功！')
        })
        .catch(error => {
            ElMessage.error(error)
        });
}

const handleSizeChange = () => {
    pageNum.value = 1
    handleSearch()
}

const handleCurrentChange = () => {
    handleSearch()
}

const getGroupOptions = () => {
    service.get('/game/getAllGroup')
        .then(response => {
            groupOptions.value = response?.data || []
        })
        .catch(error => {
            ElMessage.error(error?.message)
        });
}
onActivated(() => {
    getGroupOptions()
    handleSearch()
})

const tableRef = ref()
let sortableInstance: any = null

const initRowDrag = () => {
    if (!tableRef.value) return
    const tbody = tableRef.value?.$el?.querySelector('.el-table__body tbody')
    if (!tbody) return
    if (sortableInstance) return
    sortableInstance = new Sortable(tbody, {
        animation: 150,
        draggable: 'tr',
        onEnd: ({ oldIndex, newIndex }: any) => {
            if (oldIndex === newIndex) return
            const moved = tableData.value.splice(oldIndex, 1)[0]
            tableData.value.splice(newIndex, 0, moved)
            persistOrder()
        }
    })
}

const persistOrder = async () => {
    try {
        const ids = []
        tableData.value.forEach(item => {
            ids.push({ id: item?.id })
        })
        await service.post('/game/updateOrder', ids)
        ElMessage.success('排序已保存')
    } catch (error: any) {
        ElMessage.error(error || '保存排序失败')
    }
}
</script>

<style lang="scss">
.iaa-page {
    background-color: #fff;
    height: calc(100% - 10px);
    padding: 30px;
    width: 100%;
    box-sizing: border-box;


    .article-title {
        font-size: 20px;
        font-weight: 600;
    }

    .fliter {
        display: flex;
        align-items: center;
        margin: 30px 0;
    }

    .el-button--primary {
        background-color: #1677ff;
    }

    .article-table {
        margin-top: 50px;
        height: calc(100% - 120px);
    }

    .el-drawer {
        width: 100% !important;
    }

    .el-drawer__body {
        padding: 0;
    }

    .el-table__row {
        font-size: 13px;
        cursor: move;
    }

}
</style>
